<?php
class Sss_Grid
{
	/**
	* @var Zend_Paginator
	*/
	private $paginator = null;

	/**
	* @var array of Sss_Grid_Column_Abstract
	*/
	private $gridColumns = array();

	/**
	* @var array
	*/
	private $gridData = array();

	/**
	* @var int
	*/
	private $itemPerPage = 20;

	/**
	* @var int
	*/
	private $currentPage = 1;

	/**
	* @var Zend_View
	*/
	private $view;

	/**
	* @var array
	*/
	private $options;

	/**
	* @var array
	*/
	private $params;
	/**
	* @var string
	*/
	private $templateDir = 'grid';

	/**
	* @var string
	*/
	private $paginatorTemplate = '_paginator.phtml';

	/**
	* @var string
	*/
	private $paginatorTemplate1 = '_paginator1.phtml';

	private $nowrap = false;

	/**
	* Constructor of Grid
	* @param mixed $adapter
	* @param  $options
	* @return void
	*/
	public function __construct($adapter, array $options = null)
	{
		$this->options = array(
		'cellpadding' => 0,
		'cellspacing' => 0,
		'border' => 0,
		'width' => '100%',
		'cssRowEven' => 'row0',
		'cssRowOdd' => 'row1',
		'cssClass' => 'grid'
		);

		$this->options   = array_merge($this->options, $options);
		$this->paginator = Zend_Paginator::factory($adapter);
	}

	public function deploy()
	{
		$this->paginator->setItemCountPerPage($this->itemPerPage);
		$this->paginator->setCurrentPageNumber($this->currentPage);
		$this->gridData = $this->paginator->getItemsByPage($this->currentPage)->toArray();

		// @todo: refactor grid render and remove cheat here
		$baseIndex = ($this->paginator->getCurrentPageNumber() - 1) * $this->itemPerPage + 1;
		$length    = count($this->gridData);
		for ($i = 0; $i < $length; $i++) {
			$this->gridData[$i]['_index'] = $baseIndex + $i;
		}
	}

	public function render($part = '')
	{
		if (0 == count($this->gridData)) {
			$this->deploy();
		}
		if ('' == $part) {
			$gridHtml = "<table class='" . $this->options['cssClass'] . "'";
			$gridHtml .= 'cellspacing="' . $this->cellspacing . '" ';
			$gridHtml .= 'cellpadding="' . $this->cellpadding . '" ';
			$gridHtml .= 'border="' . $this->border . '" ';
			$gridHtml .= 'width="' . $this->width . '" ';
			$gridHtml .= ">\n";
			$gridHtml .= $this->_renderHeader();
			$gridHtml .= $this->_renderGrid();
			$gridHtml .= $this->_renderPaginator();
			$gridHtml .= "</table>";
		} else {
			$method   = '_render' . ucfirst($part);
			$gridHtml = $this->$method();
		}
		global $name, $pageName;
		return $gridHtml;
	}
	public function render1($part = '')
	{
		if (0 == count($this->gridData)) {
			$this->deploy();
		}
		if ('' == $part) {
			$gridHtml = "<table class='" . $this->options['cssClass'] . "'";
			$gridHtml .= 'cellspacing="' . $this->cellspacing . '" ';
			$gridHtml .= 'cellpadding="' . $this->cellpadding . '" ';
			$gridHtml .= 'border="' . $this->border . '" ';
			$gridHtml .= 'width="' . $this->width . '" ';
			$gridHtml .= ">\n";
			$gridHtml .= $this->_renderHeader();
			$gridHtml .= $this->_renderGrid();
			$gridHtml .= $this->_renderPaginator1();
			$gridHtml .= "</table>";
		} else {
			$method   = '_render' . ucfirst($part);
			$gridHtml = $this->$method();
		}
		global $name, $pageName;
		return $gridHtml;
	}
	protected function _renderPaginator()
	{
		$html = "  <tfoot>\n";
		$html .= "  <tr>\n";
		$html .= "    <td colspan = \"" . count($this->gridColumns) . "\">\n";
		$html .= $this->view->paginationControl($this->paginator, 'Sliding', $this->templateDir . '/' . $this->paginatorTemplate, array(
		'params' => $this->params
		));
		$html .= "    </td>\n";
		$html .= "  </tr>\n";
		$html .= "  </tfoot>\n";
		return $html;
	}
	protected function _renderPaginator1()
	{
		$html = "  <tfoot>\n";
		$html .= "  <tr>\n";
		$html .= "    <td colspan = \"" . count($this->gridColumns) . "\">\n";
		$html .= $this->view->paginationControl($this->paginator, 'Sliding', $this->templateDir . '/' . $this->paginatorTemplate1, array(
		'params' => $this->params
		));
		$html .= "    </td>\n";
		$html .= "  </tr>\n";
		$html .= "  </tfoot>\n";
		return $html;
	}
	protected function _renderHeader()
	{
		$html = "  <thead>\n";
		$html .= "  <tr>\n";
		foreach ($this->gridColumns as $columns) {
			$html .= $columns->renderHeader($this->view, $this->nowrap);
		}
		$html .= "  </tr>\n";
		$html .= "  </thead>\n";
		return $html;
	}

	protected function _renderGrid()
	{
		$gridHtml = "<tbody>\n";
		$gridHtml .= $this->_renderGridContent();
		$gridHtml .= "</tbody>\n";
		return $gridHtml;
	}

	protected function _renderGridContent()
	{
		$contentHtml = '';
		foreach ($this->gridData as $row) {
			$rowHtml = '  <tr class="' . $this->view->cycle(array(
			$this->cssRowEven,
			$this->cssRowOdd
			))->next() . '">' . "\n";
			foreach ($this->gridColumns as $column) {
				if (array_key_exists($column->key, $row)) {
					$rowHtml .= $column->renderCell($row[$column->key], $row);
				} else {
					$rowHtml .= $column->renderCell('', $row);
				}
			}
			$rowHtml .= "  </tr>\n";
			$contentHtml .= $rowHtml;
		}
		return $contentHtml;
	}

	public function setView(Zend_View_Abstract $view)
	{
		$this->view = $view;
	}

	public function __get($key)
	{
		if (isset($this->options[$key])) {
			return $this->options[$key];
		} else {
			return "";
		}
	}

	/**
	* @param int $itemPerPage
	*/
	public function setItemPerPage($itemPerPage)
	{
		$this->itemPerPage = $itemPerPage;
	}

	/**
	* @param array $params
	*/
	public function setParams(array $params = array(), $paramName = "limit", $pagName = "page")
	{
		$this->params = $params;
		if (isset($this->params[$pagName])) {
			$this->currentPage = $this->params[$pagName];
		}

		if (isset($this->params[$paramName])) {
			$this->itemPerPage = $this->params[$paramName];
		} else {
			$this->params[$paramName] = $this->itemPerPage;
		}
	}

	/**
	* Create an object include infomation about pagination 
	* @param int $limit | int $limitstart | int $total
	* @return an object
	*/

	public function createPagiObject($limit, $limitstart, $total)
	{
		$pagination                = new stdClass;
		$pagination->total         = (int) $total;
		$pagination->limit         = (int) $limit;
		$pagination->limitHardware = (int) $limit;   
		$pagination->limitstart    = (int) $limitstart;
		$pagination->pagetotal     = $limit > 0 ? (gettype($total / $limit) == 'integer' ? $total / $limit : (int) ($total / $limit) + 1) : 1;
		$pagination->pagecurrent   = (int) $limitstart / $limit + 1;
		$pagination->nextPage      = ($pagination->pagecurrent < $pagination->pagetotal) ? ($pagination->pagecurrent + 1) : $pagination->pagetotal;
		$pagination->prevPage      = ($pagination->pagecurrent > 1) ? ($pagination->pagecurrent - 1) : 1;
		$pagination->endPage       = $pagination->pagetotal;
		return $pagination;
	}

	/**
	* Render html pagination
	* @param an object
	* @return html 
	*/
	public function renderPagiHtml($pagiObject, $urlCurrent, $rootURL, $page, $queryString = null, $numberCount = null,$type = 0, $countpagging = null)
	{
		$limit = $pagiObject->limit;
		$html = '<table cellspacing="0" cellpadding="0" border="0" class="small">';
		$html .= '<tr>';
		$html .= '   <td align="right" style="padding: 0px;">';
		$id = "pagination";
		if ($countpagging) {
			$pagiObject->total = $countpagging;
		}
		if ($numberCount == null)
			$numberCount = 0;
		if (@$pagiObject->pagetotal > 1) {
			if($type == 1) {
				$limit = $pagiObject->limitHardware;
				$id = "selectHardwarePagination";
				$parameter = Sss_Ultility_CommonViewParamater::LIMIT_HARDWARE;
			} else {
				$id = "pagination";
				$parameter = Sss_Ultility_CommonViewParamater::LIMIT;
			}   
			$html .= '   <a href="' . $urlCurrent . '?'.$page.'=1&' . $parameter . '=' . $limit .$queryString.'"> <img style="cursor:pointer;" border="0" align="absmiddle"  src="' . $rootURL . '/images/start.gif" /></a>&nbsp;';
			$html .= ' <a  href="' . $urlCurrent . '?'.$page.'=' . @$pagiObject->prevPage . '&' . $parameter . '=' . $limit . $queryString.'">    <img style="cursor:pointer;" border="0" align="absmiddle"   src="' . $rootURL . '/images/previous.gif" /></a>&nbsp;';

			$html .= Resources::_('ROWS_PER_PAGE') . "<select class='small' id='{$id}' onchange='changePageSize(this, \"$urlCurrent\", \"$queryString\")'><option " . ($limit == null || $limit == 10 ? 'selected' : '') . " value='10'>10</option><option " . ($limit == 25 ? 'selected' : '') . " value='25'>25</option><option " . ($limit == 50 ? 'selected' : '') . " value='50'>50</option><option " . ($limit == 100 ? 'selected' : '') . " value='100'>100</option><option " . ($limit == -1 ? 'selected' : '') . " value='-1'>" . Resources::_('ALL') . "</option></select> ";


			$html .= '<span class="small" name=""> ' . Resources::_('PAGE') . ' ' . @$pagiObject->pagecurrent . ' ' . Resources::_('ON') . ' ' . @$pagiObject->pagetotal . ' - <span style="color: #44B444;">('.Resources::_('TOTAL').' ' . (@$pagiObject->total - $numberCount). ' '.Resources::_('ROWS').')</span></span>';
			$html .= ' <a href="' . $urlCurrent . '?'.$page.'=' . @$pagiObject->nextPage . '&' . $parameter . '=' . $limit . $queryString.'">   <img style="cursor:pointer;" border="0" align="absmiddle"   src="' . $rootURL . '/images/next.gif" /></a>&nbsp;';
			$html .= '  <a  href="' . $urlCurrent . '?'.$page.'=' . @$pagiObject->endPage . '&' . $parameter . '=' . $limit . $queryString.'">   <img style="cursor:pointer;" border="0" align="absmiddle"   src="' . $rootURL . '/images/end.gif" /></a>&nbsp;';
		} else {
			$html .= '   <img border="0" align="absmiddle"  src="' . $rootURL . '/images/start_disabled.gif" />&nbsp;';
			$html .= '     <img border="0" align="absmiddle"   src="' . $rootURL . '/images/previous_disabled.gif" />&nbsp;';
			if($type == 1) {
				$limit = $pagiObject->limitHardware; 
				$id = "selectHardwarePagination";
			}else{
				$id = "pagination";
			}
			$html .= Resources::_('ROWS_PER_PAGE') . "<select class='small' id='{$id}' onchange='changePageSize(this, \"$urlCurrent\", \"$queryString\")'><option " . ($limit == null || $limit == 10 ? 'selected' : '') . " value='10'>10</option><option " . ($limit == 25 ? 'selected' : '') . " value='25'>25</option><option " . ($limit == 50 ? 'selected' : '') . " value='50'>50</option><option " . ($limit == 100 ? 'selected' : '') . " value='100'>100</option><option " . ($limit == -1 ? 'selected' : '') . " value='-1'>" . Resources::_('ALL') . "</option></select> ";
			$html .= '<span class="small" name=""> ' . Resources::_('PAGE') . ' ' . @$pagiObject->pagecurrent . ' ' . Resources::_('ON').' ' . @$pagiObject->pagetotal . ' - <span style="color: #44B444;">('.Resources::_('TOTAL').' ' . (@$pagiObject->total - $numberCount) . ' '.Resources::_('ROWS').')</span></span>';
			$html .= '    <img border="0" align="absmiddle"   src="' . $rootURL . '/images/next_disabled.gif" />&nbsp;';
			$html .= '     <img border="0" align="absmiddle"   src="' . $rootURL . '/images/end_disabled.gif" />&nbsp;';
		}

		$html .= ' </td>';
		$html .= '</tr>';
		$html .= '</table>';
		return $html;
	}



	public function ajaxPresetPagiHtml($pagiObject, $rootURL,$arrayChartId,$checkChart, $numberCount = null)
	{

		$limit = $pagiObject->limit;
		$html = '<table cellspacing="0" cellpadding="0" border="0" class="small" align="right">';
		$html .= '<tr>';
		$html .= '   <td align="right" style="padding: 0px;">';
		if($numberCount == null)
			$numberCount = 0;
		if (@$pagiObject->pagetotal > 1) {
			$html .= ' <img onclick="searchChartPreset(\''.$arrayChartId.'\',1,\''.$checkChart.'\')" style="cursor:pointer;" border="0" align="absmiddle"  src="' . $rootURL . '/images/start.gif" />&nbsp;';
			$html .= ' <img onclick="searchChartPreset(\''.$arrayChartId.'\','.@$pagiObject->prevPage.',\''.$checkChart.'\')" style="cursor:pointer;" border="0" align="absmiddle"   src="' . $rootURL . '/images/previous.gif" />&nbsp;';
			$html .= Resources::_('ROWS_PER_PAGE') . "<select class='small selectPagination' onchange=\"searchChartPreset('".$arrayChartId."',1,'".$checkChart."')\"><option " . ($limit == null || $limit == 5 ? 'selected' : '') . " value='5'>5</option><option " . ($limit == 10 ? 'selected' : '') . " value='10'>10</option><option " . ($limit == 25 ? 'selected' : '') . " value='25'>25</option><option " . ($limit == 50 ? 'selected' : '') . " value='50'>50</option><option " . ($limit == 100 ? 'selected' : '') . " value='100'>100</option><option " . ($limit == -1 ? 'selected' : '') . " value='-1'>" . Resources::_('ALL') . "</option></select> ";


			$html .= '<span class="small" name=""> ' . Resources::_('PAGE') . ' ' . @$pagiObject->pagecurrent . ' ' . Resources::_('ON') . ' ' . @$pagiObject->pagetotal . ' - <span style="color: #44B444;">('.Resources::_('TOTAL').' ' . (@$pagiObject->total - $numberCount). ' '.Resources::_('ROWS').')</span></span>';
			$html .= ' <img onclick="searchChartPreset(\''.$arrayChartId.'\','.@$pagiObject->nextPage.',\''.$checkChart.'\')" style="cursor:pointer;" border="0" align="absmiddle"   src="' . $rootURL . '/images/next.gif" />&nbsp;';
			$html .= ' <img onclick="searchChartPreset(\''.$arrayChartId.'\','.@$pagiObject->endPage.',\''.$checkChart.'\')" style="cursor:pointer;" border="0" align="absmiddle"   src="' . $rootURL . '/images/end.gif" />&nbsp;';
		} else {
			$html .= '   <img border="0" align="absmiddle"  src="' . $rootURL . '/images/start_disabled.gif" />&nbsp;';
			$html .= '     <img border="0" align="absmiddle"   src="' . $rootURL . '/images/previous_disabled.gif" />&nbsp;';

			$html .= Resources::_('ROWS_PER_PAGE') . "<select class='small selectPagination' onchange=\"searchChartPreset('".$arrayChartId."',1,'".$checkChart."')\"><option " . ($limit == null || $limit == 5 ? 'selected' : '') . " value='5'>5</option><option " . ($limit == 10 ? 'selected' : '') . " value='10'>10</option><option " . ($limit == 25 ? 'selected' : '') . " value='25'>25</option><option " . ($limit == 50 ? 'selected' : '') . " value='50'>50</option><option " . ($limit == 100 ? 'selected' : '') . " value='100'>100</option><option " . ($limit == -1 ? 'selected' : '') . " value='-1'>" . Resources::_('ALL') . "</option></select> ";

			$html .= '<span class="small" name=""> ' . Resources::_('PAGE') . ' ' . @$pagiObject->pagecurrent . ' ' . Resources::_('ON').' ' . @$pagiObject->pagetotal . ' - <span style="color: #44B444;">('.Resources::_('TOTAL').' ' . (@$pagiObject->total - $numberCount) . ' '.Resources::_('ROWS').')</span></span>';
			$html .= '    <img border="0" align="absmiddle"   src="' . $rootURL . '/images/next_disabled.gif" />&nbsp;';
			$html .= '     <img border="0" align="absmiddle"   src="' . $rootURL . '/images/end_disabled.gif" />&nbsp;';
		}

		$html .= ' </td>';
		$html .= '</tr>';
		$html .= '</table>';
		return $html;
	}

	public function renderOrder($fieldName, $orderField, $orderType, $urlCurrent, $rootURL, $orderFieldCurrent, $queryString='')
	{
		// cheat some code here, will be improve later
		$limit = isset($_GET[Sss_Ultility_CommonViewParamater::LIMIT]) ? $_GET[Sss_Ultility_CommonViewParamater::LIMIT] : Sss_Ultility_Setting::PAGE_SIZE;
		if ($orderType == 'asc') {
			$orderType = 'desc';
		} else {
			$orderType = 'asc';
		}

		if ($orderType == null)
			$orderType = 'asc';
		if ($orderFieldCurrent == $orderField)
			$html = '<a class="listFormHeaderLinks" href="' . $urlCurrent . '?' . Sss_Ultility_CommonViewParamater::LIMIT . '=' . $limit . '&ordertype=' . $orderType . '&orderfield=' . $orderField . $queryString . '"><img border="0" src="' . $rootURL . '/images/' . $orderType . '.png">&nbsp;' . $fieldName . '&nbsp;</a>';
		else
			$html = '<a class="listFormHeaderLinks"  href="' . $urlCurrent . '?' . Sss_Ultility_CommonViewParamater::LIMIT . '=' . $limit . '&ordertype=' . $orderType . '&orderfield=' . $orderField . $queryString . '">' . $fieldName . '&nbsp;</a>';
		return $html;
	}
}
